package com.wss.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wss.domain.*;
import com.wss.service.BlogService;
import com.wss.service.BlogTypeService;
import com.wss.service.CommentService;
import com.wss.util.FileUploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@Controller
public class BlogController {

    @Autowired
    private BlogService blogService;
    @Autowired
    private BlogTypeService blogTypeService;
    @Autowired
    private CommentService commentService;


    /**
     * 展示博客主页
     */
    @RequestMapping(value="/blogMain",method=RequestMethod.GET)
    public ModelAndView blogMain(Model model,HttpServletRequest request, HttpServletResponse response){
        // 布置博客分类菜单
        initBlogType(model);
        // 查询最新8条博客信息
        List<Blog> blogList = blogService.findBlogTop8();
        model.addAttribute("blogList",blogList);
        BlogType blogType = new BlogType();
        blogType.setBtypename("最新博客");
        model.addAttribute("blogType",blogType);
        return new ModelAndView("blogMain");
    }

    /**
     * 从分类按钮searchBlog查询结果异步加载到页面内
     */
    @RequestMapping(value="/searchBlog",method=RequestMethod.GET)
    public String searchBlog(int btype_id,Model model, HttpServletRequest request, HttpServletResponse response){
        // 布置分类菜单
        initBlogType(model);
        List<Blog> blogList = blogService.findBlogByTypeId(btype_id);
        BlogType blogType = blogTypeService.findBtypeNameByBtypeid(btype_id);
        model.addAttribute("blogList",blogList);
        model.addAttribute("blogType",blogType);
        return "blogMain::blog_searchres";
    }

    /**
     * 搜索框模糊查询博客
     */
    @RequestMapping(value="/searchInputBlog")
    public ModelAndView searchInputBlog(@RequestParam("searchText") String searchText, Model model){
        // 布置分类菜单
        initBlogType(model);
        searchText = searchText.trim();
        // 模糊查询博客信息
        List<Blog> blogList = blogService.findBlogBySearchInput(searchText);
        model.addAttribute("blogList",blogList);
        BlogType blogType = new BlogType();
        blogType.setBtypename("查询“"+searchText+"”搜索结果");
        model.addAttribute("blogType",blogType);
        return new ModelAndView("blogMain");
    }

    /**
     * 博客详情页
     */
    @RequestMapping(value="/blogDetail",method=RequestMethod.GET)
    public String blogDetail(int b_id, Model model){
        Blog blog = blogService.findBlogById(b_id);
        //根据b_id查询出博客的所有评论
        List<Comment> commentList = commentService.findCommentByBlogId(b_id);
        model.addAttribute("blog",blog);
        model.addAttribute("commentList",commentList);
        return "blogDetail";
    }

    /**
     * 博客编辑页
     */
    @RequestMapping(value="/blogWrite")
    public String blogWrite(Model model, HttpServletRequest request, HttpServletResponse response){
        HttpSession session = request.getSession();
        Account account = (Account) session.getAttribute("Account");
        // 从session中拿到当前用户id
        int u_id = account.getId();
        //查询所有博客分类放入下拉框
        List<BlogType> blogTypeList = blogTypeService.findType();
        model.addAttribute("u_id",u_id);
        model.addAttribute("blogTypeList",blogTypeList);
        return "blogWrite";
    }

    /**
     * 博客修改页
     */
    @RequestMapping(value="/blogChange",method=RequestMethod.GET)
    public String blogChange(int b_id, Model model, HttpServletRequest request, HttpServletResponse response){
        // 根据userInfo页面修改博客按钮传递过来博客的id查询博客
        Blog blog = blogService.findBlogById(b_id);
        model.addAttribute("blog",blog);
        //查询所有博客分类放入下拉框
        List<BlogType> blogTypeList = blogTypeService.findType();
        model.addAttribute("blogTypeList",blogTypeList);
        return "blogChange";
    }

    /**
     * Markdown博客图片上传接口
     */
    @RequestMapping(value="/mkImageUpload", produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public String mkImageUpload(@RequestParam(value = "editormd-image-file", required = true) MultipartFile file,HttpServletRequest request){
        System.out.println("==============进入到/mkImageUpload=============");
        //创建文件上传工具类对象，调用上传方法并返回文件保存的路径
        FileUploadUtil fileUploadUtil = new FileUploadUtil();
        JSONObject res = new JSONObject();
        try {
            String mkImgUrl = fileUploadUtil.uploadMkImage(file, request);
            //返回给前端
            res.put("url", mkImgUrl);
            res.put("success", 1);
            res.put("message", "上传成功!");
        }catch (IllegalStateException | IOException e) {
            res.put("success", 0);
            res.put("message", "上传失败!");
        }
        return JSON.toJSONString(res);
    }

    /**
     * 接口测试
     */
    @RequestMapping(value="/testInterface", produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public String testInterface(HttpServletRequest request){
        System.out.println("==============进入到/testInterface=============");
        JSONObject res = new JSONObject();
        res.put("success", 1);
        res.put("message", "测试成功!");
        return JSON.toJSONString(res);
    }


    /**
     * 布置博客分类菜单
     */
    public void initBlogType(Model model){
        List<BlogType> qianduanList = blogTypeService.findBlogTypeByBthid(1);
        List<BlogType> houduanList = blogTypeService.findBlogTypeByBthid(2);
        List<BlogType> shujukuList = blogTypeService.findBlogTypeByBthid(3);
        List<BlogType> wangluoList = blogTypeService.findBlogTypeByBthid(4);
        model.addAttribute("qianduanList",qianduanList);
        model.addAttribute("houduanList",houduanList);
        model.addAttribute("shujukuList",shujukuList);
        model.addAttribute("wangluoList",wangluoList);
    }

    /**
     * 添加博客
     */
    @RequestMapping(value="/addBlog", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public String addBlog(Blog blog, HttpServletRequest request) {
        System.out.println("==============进入到/addBlog=============");
        Message message = blogService.addBlog(blog);
        String msg = JSON.toJSONString(message);
        return msg;
    }

    /**
     * 修改博客信息
     */
    @RequestMapping(value="/changeBlog", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public String changeBlog(Blog blog, HttpServletRequest request) {
        System.out.println("==============进入到/changeBlog=============");
        Message message = blogService.changeBlog(blog);
        String msg = JSON.toJSONString(message);
        return msg;
    }

    /**
     * 删除博客
     */
    @RequestMapping(value="/deleteBlog", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public String deleteBlog(Blog blog){
        System.out.println("==============进入到/deleteBlog=============");
        // 返回给前端的信息对象
        Message message = blogService.deleteBlog(blog.getId());
        String msg = JSON.toJSONString(message);
        return msg;
    }


}
